package com.besall.allbase.view.activity.chipstoollevel4.customercmd;

//import static com.bes.bessdk.BesSdkConstants.BES_CONNECT_ERROR;
//import static com.bes.bessdk.service.customcmd.CustomCmdConstants.OP_TOTA_SET_CUSTOMER_CMD;
//import static com.besall.allbase.bluetooth.BluetoothConstants.Scan.BES_SCAN_RESULT;
//import static com.besall.allbase.common.Constants.CHIPS_FILE_PATH_RESULT;
//import static com.besall.allbase.common.Constants.FILE_CODE;
//import static com.besall.allbase.common.utils.FileUtils.getFolderPath;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.bes.bessdk.BesSdkConstants;
import com.bes.bessdk.connect.BTService;
import com.bes.bessdk.scan.BtHeleper;
import com.bes.bessdk.service.base.BesServiceConfig;
import com.bes.bessdk.service.base.BesServiceListener;
import com.bes.bessdk.service.customcmd.CustomCmdConstants;
import com.bes.bessdk.utils.ArrayUtil;
import com.bes.bessdk.utils.CmdInfo;
import com.bes.bessdk.utils.SPHelper;
import com.bes.sdk.device.HmDevice;
import com.bes.sdk.utils.DeviceProtocol;
import com.besall.allbase.bluetooth.BluetoothConstants;
import com.besall.allbase.common.Constants;
import com.besall.allbase.common.utils.ActivityUtils;
import com.besall.allbase.common.utils.FileUtils;
import com.besall.allbase.common.utils.SharedPreferencesUtils;
import com.besall.allbase.view.base.BaseActivity;

import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.Editable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.method.ScrollingMovementMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.PopupWindow;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.IdRes;

import bb.lanxing.R;

/**
 * @author ericshen
 * @time $ $
 */
public class CustomCmdActivity extends BaseActivity<ICustomCmdActivity, CustomCmdPresenter>
        implements ICustomCmdActivity, BesServiceListener, View.OnClickListener, TextWatcher {
    private static final int FileCode = 1;
    private static final int RESULT_CODE = 101;
    private static CustomCmdActivity instance;
    public String cur_title = "CUSTOM CMD";
    BluetoothDevice mDevice;
    HmDevice mHmDevice;
    BesServiceConfig mServiceConfig;
    byte[] bytes = new byte[256];
    byte[] showInfo = new byte[30];
    byte[] cmdsend = new byte[260];
    List<Select> getData = null;
    List<Select> data = new ArrayList<>();
    private String startTime = "";
    private Button pick_device;
    private Button pick_device_ble;
    private Button connect_device;
    private TextView device_address;
    private TextView device_name;
    private Button edit_cutomercmd;
    private Button spp_stop;
    private ImageButton data_send;
    private EditText cmd_ed;
    private Button importCmd;
    private Button cmd_save;
    private TextView file_path;
    private TextView cmdInfo;
    private TextView receive_info;
    private RelativeLayout cmd_typing;
    private Spinner dataMode;
    private RadioGroup cmd_header;
    private RadioGroup cmd_need_efffective_length;
    private String account;
    private Boolean flag = false;
    private Context mContext = CustomCmdActivity.this;
    public RemoveUserinfoListner removeUserinfoListner = new RemoveUserinfoListner() {
        @Override
        public void removeuserinfosuccess(int position, List<Select> data) {
            if (data != null && data.size() > 0) {
                data.remove(position);
                SharedPreferencesUtils.putSelectBean(mContext, data, "selectphone");
                flag = false;
                List<Select> getdata = SharedPreferencesUtils.getSelectBean(instance, "selectphone");
                if (getdata != null && getdata.size() > 0) {
                    Select selectPhone = getdata.get(0);
                    cmd_ed.setText(selectPhone.getName());

                } else {
                    cmd_ed.setText(null);
                }
            } else {
                Toast.makeText(mContext, "缓存数据为空", Toast.LENGTH_LONG).show();
            }
        }

    };
    private TextView textView;
    private SpinerPopWindow<Select> mSpinerPopWindow;
    private int mode = 0;
    private boolean useHeader = true;
    private boolean needEfffectiveLength = false;
    private final RadioGroup.OnCheckedChangeListener useHeaderCheckedChangedListener =
            new RadioGroup.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {

                    if (checkedId == R.id.use_cmd_header) {
                        useHeader = true;
                        cmdShow();
                    } else if (checkedId == R.id.nouse_cmd_header) {
                        useHeader = false;
                        cmdShow();
                    } else if (checkedId == R.id.cmd_need_efffective_length_no) {
                        needEfffectiveLength = false;
                        cmdShow();
                    } else if (checkedId == R.id.cmd_need_efffective_length_yes) {
                        needEfffectiveLength = true;
                        cmdShow();
                    }

                    /*
                     * switch (checkedId) { case R.id.use_cmd_header: useHeader = true; cmdShow(); break; case
                     * R.id.nouse_cmd_header: useHeader = false; cmdShow(); break; case
                     * R.id.cmd_need_efffective_length_no: needEfffectiveLength = false; cmdShow(); break; case
                     * R.id.cmd_need_efffective_length_yes: needEfffectiveLength = true; cmdShow(); break; default:
                     * break; }
                     */
                }
            };
    private PopupWindow.OnDismissListener dismissListener = new PopupWindow.OnDismissListener() {
        @Override
        public void onDismiss() {
            flag = false;
        }
    };
    private AdapterView.OnItemClickListener itemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            mSpinerPopWindow.dismiss();
            flag = false;
            Select selectPhone = getData.get(position);
            String getUserName = selectPhone.getName();
            cmd_ed.setText(getUserName);
            cmdShow();

        }
    };

    @Override
    protected CustomCmdPresenter createPresenter() {
        return new CustomCmdPresenter();
    }

    @Override
    protected void initBeforeSetContent() {
        mServiceConfig = new BesServiceConfig();
    }

    @Override
    protected int getContentViewId() {
        return R.layout.act_connect;
    }

    @Override
    protected void bindView() {
        pick_device = (Button) findViewById(R.id.pick_device);
        pick_device_ble = (Button) findViewById(R.id.pick_device_ble);
        connect_device = (Button) findViewById(R.id.connect_device);
        device_address = (TextView) findViewById(R.id.device_address_connect);
        device_name = (TextView) findViewById(R.id.device_name);
        edit_cutomercmd = (Button) findViewById(R.id.edit_cutomercmd);

        loadanimdrawable();

    }

    @Override
    protected void initView() {
        inittoolbar(cur_title);
        pick_device.setOnClickListener(instance);
        pick_device_ble.setOnClickListener(instance);
        pick_device_ble.setVisibility(View.VISIBLE);
        connect_device.setOnClickListener(instance);
        edit_cutomercmd.setVisibility(View.VISIBLE);
        edit_cutomercmd.setOnClickListener(instance);
        logV = (TextView) findViewById(R.id.logV);
        done = (Button) findViewById(R.id.done);
        scr_policy = (ScrollView) findViewById(R.id.scr_policy);
        loginfo = (View) findViewById(R.id.loginfo);

        tv_title.setOnClickListener(instance);
        done.setOnClickListener(instance);

        logV.setMovementMethod(ScrollingMovementMethod.getInstance());
        scr_policy.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                v.getParent().requestDisallowInterceptTouchEvent(true);
                return false;
            }
        });

        // connect_spp.setOnClickListener(instance);
        // spp_stop.setOnClickListener(instance);
        // data_send.setOnClickListener(instance);
        // select_cmd_rl.setOnClickListener(instance);
        // ImportCmd.setOnClickListener(instance);
        // cmd_save.setOnClickListener(instance);

        // getlistdata();

    }

    @Override
    protected void setInstance() {
        instance = this;
    }

    @Override
    protected void removeInstance() {
        instance = null;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == BluetoothConstants.Scan.REQUEST_CODE_SCAN) {
            onPickDevice(resultCode, data);
        }

        if (requestCode == Constants.FILE_CODE) {
            if (resultCode == Constants.CHIPS_FILE_PATH_RESULT) {
                final String jsonfile = data.getStringExtra("getFilePath");
                Log.i(TAG, "onClick: ++++++" + jsonfile);
                Log.i(TAG, "onActivityResult: +++++++++" + data.getIntExtra("getFilePath", 100));
                // 获取json后写入list
                List<Select> getdata = SharedPreferencesUtils.readbysd(new File(jsonfile));
                SharedPreferencesUtils.putSelectBean(instance, getdata, "selectphone");
                initView();
                if (file_path != null) {
                    file_path.setText(jsonfile);
                }
            }
        }
    }

    private void onPickDevice(int resultCode, Intent data) {
        if (resultCode == RESULT_OK) {
            mHmDevice = (HmDevice) data.getSerializableExtra(BluetoothConstants.Scan.BES_SCAN_RESULT);
            mDevice = BtHeleper.getBluetoothAdapter(instance).getRemoteDevice(
                    mHmDevice.getPreferredProtocol() == DeviceProtocol.PROTOCOL_BLE ? mHmDevice.getBleAddress()
                            : mHmDevice.getDeviceMAC());

            Log.i(TAG, "onPickDevice: " + mDevice.getName());
            Log.i(TAG, "onPickDevice: " + mDevice.getAddress());
            device_address.setText(mDevice.getAddress());
            mServiceConfig.setDevice(mHmDevice);
            String name = mDevice.getName();
            SpannableString ss = new SpannableString(name);
            BesSdkConstants.BesConnectState state = BTService.getDeviceConnectState(instance, mServiceConfig);
            Log.i(TAG, "onPickDevice: -------" + state);
            if (state == BesSdkConstants.BesConnectState.BES_CONNECT) {
                ss.setSpan(new ForegroundColorSpan(Color.rgb(103, 200, 77)), 0, name.length(),
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
            device_name.setText(ss);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            finish();
        } else if (item.getItemId() == R.id.menu_file) {
            mPresenter.selectfile(instance, Constants.FILE_CODE);
        }

        /*
         * switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.menu_file:
         * mPresenter.selectfile(instance,Constants.FILE_CODE); break; }
         */
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onClick(View v) {

        if (v.getId() == R.id.pick_device) {
            mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_SPP);
            connect_device.setVisibility(View.VISIBLE);
            mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
            mServiceConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT);
        } else if (v.getId() == R.id.pick_device_ble) {
            mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
            connect_device.setVisibility(View.VISIBLE);
            mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
            mServiceConfig.setServiceUUID(BesSdkConstants.BES_TOTA_SERVICE_OTA_UUID);
            mServiceConfig.setCharacteristicsUUID(BesSdkConstants.BES_TOTA_CHARACTERISTI_OTA_UUID);
            mServiceConfig.setDescriptorUUID(BesSdkConstants.BES_TOTA_DESCRIPTOR_OTA_UUID);
        } else if (v.getId() == R.id.connect_device) {
            // initlayout();
            loadinganim();
            if (mHmDevice == null) {
                loadingDialog.dismiss();
                ActivityUtils.showToast(R.string.connect_failed);
                return;
            }
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i(TAG, "run: 1");
                    mServiceConfig.setDevice(mHmDevice);
                    Log.i(TAG, "onPickDevice:1111 " + mDevice.getAddress());
                    mServiceConfig.setTotaConnect(true);
                    boolean useTotaV2 = (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_TOTA_USE_TOTAV2,
                            BesSdkConstants.BES_TOTA_USE_TOTAV2_VALUE);
                    mServiceConfig.setUseTotaV2(useTotaV2);
                    mPresenter.connectDevice(mServiceConfig, instance, instance);
                }
            });
        } else if (v.getId() == R.id.edit_cutomercmd) {
            initLayout();
        } else if (v.getId() == R.id.ImportCmd) {

            mPresenter.importfile(instance, Constants.FILE_CODE);

        } else if (v.getId() == R.id.cmd_save) {

            account = cmd_ed.getText().toString();
            saveToFile();

        } else if (v.getId() == R.id.done) {

            Log.i(TAG, "onClick: 112313132");
            loginfo.setVisibility(View.GONE);

        } else if (v.getId() == R.id.tv_title) {
            loginfo.setVisibility(View.VISIBLE);
        }

        /*
         * switch (v.getId()) { case R.id.pick_device: mPresenter.pickDecice(instance,
         * BluetoothConstants.Scan.SCAN_SPP); connect_device.setVisibility(View.VISIBLE);
         * mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_SPP);
         * mServiceConfig.setServiceUUID(BesSdkConstants.BES_SPP_CONNECT); break; case R.id.pick_device_ble:
         * mPresenter.pickDecice(instance, BluetoothConstants.Scan.SCAN_BLE);
         * connect_device.setVisibility(View.VISIBLE); mServiceConfig.setDeviceProtocol(DeviceProtocol.PROTOCOL_BLE);
         * mServiceConfig.setServiceUUID(BesSdkConstants.BES_TOTA_SERVICE_OTA_UUID);
         * mServiceConfig.setCharacteristicsUUID(BesSdkConstants.BES_TOTA_CHARACTERISTI_OTA_UUID);
         * mServiceConfig.setDescriptorUUID(BesSdkConstants.BES_TOTA_DESCRIPTOR_OTA_UUID); break; case
         * R.id.connect_device: // initlayout(); loadinganim(); if (mHmDevice == null) { loadingDialog.dismiss();
         * ActivityUtils.showToast(R.string.connect_failed); return; } runOnUiThread(new Runnable() {
         *
         * @Override public void run() { Log.i(TAG, "run: 1"); mServiceConfig.setDevice(mHmDevice); Log.i(TAG,
         * "onPickDevice:1111 " + mDevice.getAddress()); mServiceConfig.setTotaConnect(true); boolean useTotaV2 =
         * (boolean) SPHelper.getPreference(instance, BesSdkConstants.BES_TOTA_USE_TOTAV2,
         * BesSdkConstants.BES_TOTA_USE_TOTAV2_VALUE); mServiceConfig.setUseTotaV2(useTotaV2);
         * mPresenter.connectDevice(mServiceConfig, instance, instance); } }); // initlayout(); break; case
         * R.id.edit_cutomercmd: initLayout(); break;
         *
         * // case R.id.select_cmd_rl: // if (flag) { // flag = false; // if (mSpinerPopWindow != null) { //
         * mSpinerPopWindow.dismiss(); // } else { // // } // } else { // flag = true; // if (mSpinerPopWindow != null)
         * { // mSpinerPopWindow.showAsDropDown(textView); // } else { // } // // } // break; case R.id.ImportCmd:
         * mPresenter.importfile(instance, Constants.FILE_CODE); break; case R.id.cmd_save:
         * account=cmd_ed.getText().toString(); saveToFile(); break; case R.id.done: Log.i(TAG, "onClick: 112313132");
         * loginfo.setVisibility(View.GONE); break; case R.id.tv_title: loginfo.setVisibility(View.VISIBLE); break;
         * default: break;
         *
         * }
         */
    }

    @Override
    public void onTotaConnectState(boolean state, HmDevice hmDevice) {
        runOnUiThread(() -> {
            if (state) {
                initLayout();
                loadingDialog.dismiss();
            }
        });
    }

    @Override
    public void onErrorMessage(int msg, HmDevice hmDevice) {

    }

    @Override
    public void onStateChangedMessage(int msg, String msgStr, HmDevice hmDevice) {
        Log.i(TAG, "onStateChangedMessage: +" + msgStr);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg == BesSdkConstants.BES_CONNECT_ERROR) {
                    Log.i(TAG, "run: failed");
                    loadingDialog.dismiss();
                    ActivityUtils.showToast(R.string.connect_failed);
                }
                if (msg == BesSdkConstants.TOTA_LOG_INFO) {
                    addlog(ArrayUtil.toHex(BTService.getCurSendData()));
                    addlog(msgStr);
                    receive_info.setText(msgStr);
                }
                // if (msg == CustomCmdConstants.showcmdinfo) {
                // cmdinfo.setText(msgStr);
                // }
            }
        });
    }

    @Override
    public void onSuccessMessage(int msg, HmDevice hmDevice) {

    }

    public void cmdChange() {
        String name = cmd_ed.getText().toString();
        String name16 = ArrayUtil.str2HexStr(name);
        byte[] namebytes = ArrayUtil.toBytes(name16);
        if (needEfffectiveLength && useHeader) {
            namebytes = ArrayUtil.byteMerger(new byte[] { ArrayUtil.intToBytesLittle(namebytes.length)[0],
                    ArrayUtil.intToBytesLittle(namebytes.length)[1] }, namebytes);
        }
        bytes = new byte[256];
        for (int i = 0; i < namebytes.length; i++) {
            bytes[i] = namebytes[i];
        }
    }

    public void cmdShow() {
        if (mode == 0) {
            cmdChange();
            Log.i(TAG, "cmdshow:cmdchange ");
            Log.i(TAG, "senddatainfo: ++++++" + ArrayUtil.toHex(bytes));
            if (useHeader) {
                CmdInfo curcmd = new CmdInfo(CustomCmdConstants.OP_TOTA_SET_CUSTOMER_CMD, bytes);
                System.arraycopy(curcmd.toBytes(), 0, showInfo, 0, 30);
                bytes = curcmd.toBytes();
            } else {
                System.arraycopy(bytes, 0, showInfo, 0, 30);
            }
            cmdInfo.setText(ArrayUtil.toHex(showInfo));
        } else if (mode == 1) {
            try {
                showInfo = new byte[30];
                String cmd16 = cmd_ed.getText().toString().replace("," + " ", "");
                byte[] byte16 = ArrayUtil.toBytes(cmd16);
                if (needEfffectiveLength && useHeader) {
                    byte16 = ArrayUtil.byteMerger(new byte[] { ArrayUtil.intToBytesLittle(byte16.length)[0],
                            ArrayUtil.intToBytesLittle(byte16.length)[1] }, byte16);
                }
                bytes = new byte[256];
                for (int i = 0; i < byte16.length; i++) {
                    bytes[i] = byte16[i];
                }
                if (useHeader) {
                    CmdInfo curcmd = new CmdInfo(CustomCmdConstants.OP_TOTA_SET_CUSTOMER_CMD, bytes);
                    Log.i(TAG, "cmdshow: 16----" + ArrayUtil.toHex(curcmd.toBytes()));
                    System.arraycopy(curcmd.toBytes(), 0, showInfo, 0, 30);
                    bytes = curcmd.toBytes();
                } else {
                    System.arraycopy(bytes, 0, showInfo, 0, 30);
                }
                cmdInfo.setText(ArrayUtil.toHex(showInfo));
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        cmdShow();
    }

    @Override
    public void afterTextChanged(Editable s) {

    }

    private void saveList() {
        account = cmd_ed.getText().toString();
        Select selectPhone = new Select();
        selectPhone.setName(account);
        List<Select> getData = SharedPreferencesUtils.getSelectBean(instance, "selectphone");
        if (getData != null) {
            for (int i = 0; i < getData.size(); i++) {
                Select mSelect = getData.get(i);
                if (mSelect.getName().equals(account)) {
                    return;
                }
            }
        }
        if (getData != null && getData.size() > 0) {
            getData.add(0, selectPhone);
            SharedPreferencesUtils.putSelectBean(instance, getData, "selectphone");
        } else {
            data.add(selectPhone);
            SharedPreferencesUtils.putSelectBean(instance, data, "selectphone");
        }
        Toast.makeText(mContext, "数据缓存成功", Toast.LENGTH_LONG).show();
        initView();
    }

    public String creatfilepath() {

        String dirPath = FileUtils.getFolderPath() + "BES/" + "LogData/" + CustomCmdConstants.CUSTOM_CMD_SAVE_FOLDER;
        FileUtils.isExist(dirPath);
        Log.i(TAG, "creatfilepath: " + dirPath);
        if (startTime.length() == 0) {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
            Date date = new Date(System.currentTimeMillis());
            startTime = simpleDateFormat.format(date);
        }
        String filePath = dirPath + "/" + startTime + "_cmd.txt";
        return filePath;
    }

    private void saveToFile() {
        Select selectPhone = new Select();
        selectPhone.setName(account);
        List<Select> getdata = SharedPreferencesUtils.getSelectBean(instance, "selectphone");
        Log.i(TAG, "saveToFile: ---" + getdata);
        if (getdata != null && getdata.size() > 0) {
            getdata.add(0, selectPhone);
            SharedPreferencesUtils.putSelectBean(instance, getdata, "selectphone");
            // SharedPreferencesUtils.storetosd(new File(creatfilepath()), getdata);
            FileUtils.writeTOFile(getdata.toString(), CustomCmdConstants.CUSTOM_CMD_SAVE_FOLDER, "cmd", "txt");
        } else {
            data.add(selectPhone);
            // SharedPreferencesUtils.storetosd(new File(creatfilepath()), getdata);
            FileUtils.writeTOFile(getdata.toString(), CustomCmdConstants.CUSTOM_CMD_SAVE_FOLDER, "cmd", "txt");
        }
        Toast.makeText(mContext, "save to sd", Toast.LENGTH_LONG).show();
        initView();
    }

    public void getlistdata() {
        getData = SharedPreferencesUtils.getSelectBean(mContext, "selectphone");
        mSpinerPopWindow = new SpinerPopWindow<Select>(instance, getData, itemClickListener, removeUserinfoListner);
        mSpinerPopWindow.setOnDismissListener(dismissListener);
    }

    public void initLayout() {
        setContentView(R.layout.activity_cuscmd);
        inittoolbar(cur_title);
        spp_stop = findViewById(R.id.spp_stop);
        data_send = findViewById(R.id.data_send);
        importCmd = findViewById(R.id.ImportCmd);
        cmd_save = findViewById(R.id.cmd_save);
        cmd_ed = findViewById(R.id.cmd_ed);
        file_path = findViewById(R.id.file_path);
        cmdInfo = findViewById(R.id.cur_cmd_info);
        receive_info = findViewById(R.id.receive_info);
        cmd_ed.addTextChangedListener(instance);
        cmd_typing = findViewById(R.id.cmd_typing);
        textView = findViewById(R.id.login_account_textview);
        cmd_ed.setOnTouchListener((v, event) -> {
            final int DRAWABLE_RIGHT = 2;
            if (event.getAction() == MotionEvent.ACTION_UP) {
                if (event.getX() >= (cmd_ed.getWidth()
                        - cmd_ed.getCompoundDrawables()[DRAWABLE_RIGHT].getBounds().width() - 10)) {
                    // your action here
                    Log.i(TAG, "onClick: select");
                    if (flag) {
                        flag = false;
                        if (mSpinerPopWindow != null) {
                            mSpinerPopWindow.dismiss();
                        } else {

                        }
                    } else {
                        flag = true;
                        if (mSpinerPopWindow != null) {
                            mSpinerPopWindow.showAsDropDown(textView);
                            getlistdata();
                        } else {
                        }

                    }
                    // cmd_ed.setCompoundDrawablesWithIntrinsicBounds(null, null,
                    // getResources().getDrawable(R.drawable.pull_up1), null);
                    return true;
                }
            }

            return false;
        });
        data_send.setOnClickListener(v -> {
            Log.i(TAG, "onClick: -----" + ArrayUtil.toHex(bytes));
            mPresenter.sendCustomCommand(bytes);
            saveList();
        });
        importCmd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPresenter.importfile(instance, Constants.FILE_CODE);
            }
        });
        cmd_save.setOnClickListener(v -> {
            account = cmd_ed.getText().toString();
            saveToFile();
        });
        spp_stop.setOnClickListener(v -> mPresenter.stopSpp());
        mToolbar.setNavigationOnClickListener(v -> backToConnect());
        getlistdata();

        tv_title.setOnClickListener(instance);
        logV = (TextView) findViewById(R.id.logV);
        done = (Button) findViewById(R.id.done);
        scr_policy = (ScrollView) findViewById(R.id.scr_policy);
        loginfo = (View) findViewById(R.id.loginfo);
        logV.setMovementMethod(ScrollingMovementMethod.getInstance());
        done.setOnClickListener(instance);
        scr_policy.setOnTouchListener((v, event) -> {
            v.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        });

        dataMode = (Spinner) findViewById(R.id.datamode);
        String[] sourcemode = new String[] { "10 Decimal", "16 Hex" };
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.simple_spinner_item, sourcemode);
        adapter.setDropDownViewResource(R.layout.support_simple_spinner_dropdown_item);
        dataMode.setAdapter(adapter);
        dataMode.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                String res = parent.getItemAtPosition(position).toString();
                mode = position;
                if (mode == 1) {
                    Log.i(TAG, "onItemSelected: 1");
                    String transferresult = cmd_ed.getText().toString().replace("," + " ", "");
                    cmd_ed.setText(transferresult);
                }
                Toast.makeText(instance, res, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        cmd_header = (RadioGroup) findViewById(R.id.cmd_header);
        cmd_header.setOnCheckedChangeListener(useHeaderCheckedChangedListener);

        cmd_need_efffective_length = (RadioGroup) findViewById(R.id.cmd_need_efffective_length);
        cmd_need_efffective_length.setOnCheckedChangeListener(useHeaderCheckedChangedListener);
    }

    public void backToConnect() {
        setContentView(R.layout.act_connect);
        bindView();
        initView();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_documents, menu);

        return true;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // mPresenter.stopSpp();
    }
}
